package cn.ybk.product.controller;

import cn.ybk.product.dto.PurchaseDto;
import cn.ybk.product.service.IProductService;
import cn.ybk.product.domain.Product;
import cn.ybk.product.query.ProductQuery;
import cn.ybk.basic.util.AjaxResult;
import cn.ybk.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    public IProductService productService;


    /**
     * 保存和修改公用的
     *
     * @param product 传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Product product) {
        try {
            if (product.getId() != null)
                productService.update(product);
            else
                productService.add(product);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            productService.delete(id);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public Product get(@PathVariable("id") Long id) {
        return productService.findById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    public List<Product> list() {
        return productService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public PageList<Product> json(@RequestBody ProductQuery query) {
        return productService.queryByPage(query);
    }


    /**
     * 上架
     */
    @PostMapping("/onsale")
    public AjaxResult onsale(@RequestBody List<Long> ids) {
        productService.onsale(ids);
        return AjaxResult.me().success();
    }

    // 下架
    @PostMapping("/offsale")
    public AjaxResult offsale(@RequestBody List<Long> ids) {
        productService.offsale(ids);
        return AjaxResult.me().success();
    }

    // 购买
    @PostMapping("/purchase")
    public AjaxResult purchase(@RequestBody PurchaseDto dto) {
        productService.purchase(dto);
        return AjaxResult.me().success();
    }




}
